/**    
 * @{#} CommonUtility.java Create on 2014-5-18 下午2:37:27    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.TextView;
import cn.o.app.event.listener.OBitmapLoadCallBack;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.ui.OImageView;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.task.RequestTask;
import com.igexin.sdk.PushManager;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.PersonHomeActivity;
import com.smiier.skin.RegisterSecondStepActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.UserExtra;
import com.smiier.skin.net.UserGetTask;
import com.smiier.skin.net.UserGetTask.UserGetRequest;
import com.smiier.skin.net.UserGetTask.UserGetResponse;
import com.smiier.skin.net.UserSetTask;
import com.smiier.skin.net.UserSetTask.UserSetRequest;
import com.smiier.skin.net.entity.Hospital.HospitalItem;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.util.GlobalSettings;

@SuppressLint("UseSparseArrays")
public class CommonUtility extends com.evan.common.utils.CommonUtility {

	public static final HashMap<Integer, String> sex = new HashMap<Integer, String>();
	public static final HashMap<Integer, Boolean> xuanshang = new HashMap<Integer, Boolean>();
	public static final HashMap<Integer, String> huaiyun = new HashMap<Integer, String>();
	public static final HashMap<Integer, String> marry = new HashMap<Integer, String>();

	// 固话参数中不需要校验的字段
	static HashMap<String, Object> dataVesrionFilter = new HashMap<String, Object>();
	static {
		sex.put(0, "男");
		sex.put(1, "女");

		xuanshang.put(0, false);
		xuanshang.put(1, true);

		marry.put(0, "未婚");
		marry.put(1, "已婚");

		huaiyun.put(0, "未孕");
		huaiyun.put(1, "怀孕");

		dataVesrionFilter.put("Update", 1);
		dataVesrionFilter.put("AndroidUpdate", 1);
		dataVesrionFilter.put("IOSUpdate", 1);
	}

	public static boolean response200(JSONObject object) {
		try {
			if (!CommonUtility.isNull(object)) {
				return 200 == object.getInt(Constant.JSON_PARAM_RESCODE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static JSONObject responseRes(JSONObject object) {
		try {
			if (!CommonUtility.isNull(object)) {
				return object.getJSONObject(Constant.JSON_PARAM_RES);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String info(JSONObject object) {
		try {
			if (!CommonUtility.isNull(object)) {
				return object.getString(Constant.JSON_PARAM_RESULTMESSAGE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getAgeByBirthday(String birthday) {
		if (!CommonUtility.isNull(birthday)) {
			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(Calendar.YEAR);
			int birthday_year = Integer.parseInt(birthday.substring(0, 4));
			int age = year - birthday_year;
			if (age > 2000) {
				age = 0;
			}
			return String.valueOf(age);
		}
		return "0";
	}

	public static boolean isDoctor() {
		try {

			/*
			 * 暂时把User_Type 值为1
			 */

			/* GlobalSettings.sUser.User_Type = 1; */
			if (Constant.TYPE_DOCTOR == GlobalSettings.sUser.User_Type) {
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	public static boolean isCert() {
		try {
			if (GlobalSettings.sUser.Is_Cert == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	public static boolean isMineQuestion(JSONObject user) {
		try {
			if (GlobalSettings.sUid == user.getInt("Doctor_Uid")) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void putAll(JSONArray dst, JSONArray src, int qid) {
		try {
			JSONObject object = null;
			for (int i = 0; i < src.length(); i++) {
				object = src.getJSONObject(i);
				if (object.getInt("Qid") != qid) {
					dst.put(src.get(i));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void putAll(ArrayList<Object> list, JSONArray src, int qid) {
		try {
			JSONObject object = null;
			for (int i = 0; i < src.length(); i++) {
				object = src.getJSONObject(i);
				if (object.getInt("Qid") != qid) {
					list.add(object);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String convertJSONArray2String(JSONArray array, String spec) {
		StringBuilder sb = new StringBuilder();
		try {
			for (int i = 0; i < array.length(); i++) {
				sb.append(array.getString(i));
				if (i < array.length() - 1) {
					sb.append(spec);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static int convertString2Index(String data,
			HashMap<Integer, String> map) {
		if (!CommonUtility.isNull(data)) {
			for (Integer key : map.keySet())
				if (map.get(key).equals(data))
					return key;
		}
		return 0;
	}

	/**
	 * 检查服务端固话数据是否有更新 method desc：
	 * 
	 * @param activity
	 * @param isShowDialog
	 */
	@SuppressWarnings("unchecked")
	public static void checkDataVersion(final Activity activity,
			final boolean isShowDialog) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put(Constant.PARAM_API, "Sys.GetVer");
		new RequestTask(activity, Constant.URL.REQUEST, new RequestHandler(
				activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							try {
								JSONArray array = object
										.getJSONArray(Constant.JSON_PARAM_RES);
								if (array.length() > 0) {
									SharedPreferences preferences = getSharedPreferences(activity);
									boolean isReCreated = false;
									for (int i = 0; i < array.length(); i++) {
										JSONObject item = array
												.getJSONObject(i);
										String name = item.getString("Name");
										if (dataVesrionFilter.containsKey(name)) {
											continue;
										}
										String currentVersion = item
												.getString("Ver");
										String nowVersion = preferences
												.getString(name, "");
										if (!currentVersion.equals(nowVersion)
												&& !isReCreated) {
											DBUtil.getInstance(activity)
													.createTables();
											isReCreated = true;
										}
										preferences
												.edit()
												.putString(name, currentVersion)
												.commit();
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), isShowDialog).execute(params);
	}

	static boolean checkVersionIsNeed2Update(Activity activity,
			String serverVersion) {
		try {
			String[] currentVersionNum = getVersion(activity).split("\\.");
			String[] serverVersionNum = serverVersion.split("\\.");
			for (int i = 0; i < serverVersionNum.length; i++) {
				if (Integer.parseInt(serverVersionNum[i]) > Integer
						.parseInt(currentVersionNum[i])) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void toPersonHomeActivity(Context context, User user) {
		Intent intent = new Intent(context, PersonHomeActivity.class);
		UserExtra extra = new UserExtra();
		extra.setUser(user);
		extra.putTo(intent);
		context.startActivity(intent);
	}

	public static void confirmSendCode(final Activity activity,
			final String tel, final int operateType) {
		OAlert alert = new OAlert(activity);
		alert.setOK("确认");
		alert.setCancel("取消");
		alert.setTitle("确认手机号码");
		alert.setMessage("我们将发送验证码短信到这个号码:\n" + tel);
		alert.show();
		alert.setListener(new OAlertListener() {

			@Override
			public boolean onOK(OAlert alert) {
				try {
					Long.parseLong(tel);
					if (tel.length() > 7) {
						Intent intent = new Intent(activity,
								RegisterSecondStepActivity.class);
						intent.putExtra(Constant.IDENTITY_KEY, tel);
						intent.putExtra(Constant.IDENTITY_KEY_1, operateType);
						activity.startActivity(intent);
					}
				} catch (Exception e) {

				}
				return false;
			}

			@Override
			public boolean onCancel(OAlert alert) {
				return false;
			}
		});
	}

	public static boolean setHosLevel(String hos, TextView mHosLevel) {
		for (HospitalItem item : GlobalSettings.mHospitalItems) {
			if (hos != null && !hos.equals("")) {
				if (item.Name.equals(hos) || item.FullName.equals(hos)
						|| item.Name.contains(hos)
						|| item.FullName.contains(hos)
						|| hos.contains(item.Name)
						|| hos.contains(item.FullName)) {
					if (item.Level != null && !item.Level.equals("")) {

						String str;
						if (item.Level.contains("三级")
								&& item.Level.contains("甲")) {
							str = "公立三甲";
							mHosLevel
									.setBackgroundResource(R.drawable.round_btn_red);
						} else if (item.Level.contains("三级")) {
							str = "公立三级";
							mHosLevel
									.setBackgroundResource(R.drawable.round_btn_orange);
						} else if (item.Level.contains("二级")
								&& item.Level.contains("甲")) {
							str = "公立二甲";
							mHosLevel
									.setBackgroundResource(R.drawable.round_btn_green);
						} else if (item.Level.contains("二级")) {
							str = "公立二级";
							mHosLevel
									.setBackgroundResource(R.drawable.round_btn_blue);
						} else if (item.Level.contains("一级")) {
							str = "公立一级";
							mHosLevel
									.setBackgroundResource(R.drawable.round_btn_purple);
						} else {
							str = "民营医院";
							mHosLevel
									.setBackgroundResource(R.drawable.round_btn_red_purple);
						}
						mHosLevel.setText(str);
					} else {
						mHosLevel.setVisibility(View.GONE);
					}
					return true;
				}
			}
		}
		return false;
	}

	public static void displayHeadImage(final OImageView mImage,
			BitmapUtils mBitmapUtils, String pic, final Resources res, int sex) {
		final int resID;
		String type;
		Random r = new Random();
		if (sex == 0) {
			// 男
			type = "fmale_" + (r.nextInt(4) + 1);
		} else {
			// 女
			type = "male_" + (r.nextInt(4) + 1);
		}
		Field field;
		try {
			field = R.drawable.class.getField(type);
			resID = field.getInt(new R.drawable());
			if (pic == null && pic.trim().equals("")) {
				mImage.setImageResource(resID);

			} else {
				mBitmapUtils.display(mImage, pic,
						new OBitmapLoadCallBack<View>() {
							@Override
							public void onLoadFailed(View container,
									String uri, Drawable drawable) {
								mImage.setImageResource(resID);

							}
						});
			}
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void userGet(final Context context) {
		UserGetRequest req = new UserGetRequest();
		req.uids = new ArrayList<Long>();
		req.uids.add(GlobalSettings.sUid);
		UserGetTask task = new UserGetTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<UserGetTask.UserGetRequest, UserGetTask.UserGetResponse>() {

			@Override
			public void onException(
					INetTask<UserGetRequest, UserGetResponse> task, Exception e) {

			}

			@Override
			public void onComplete(
					INetTask<UserGetRequest, UserGetResponse> task,
					UserGetResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				if (response.Res == null) {
					return;
				}
				if (response.Res.size() > 0) {
					GlobalSettings.sUser = response.Res.get(0);
					setGTClientId(context);
					Intent intent = new Intent(Constant.RECIVER_QUESTION);
					intent.putExtra(Constant.IDENTITY_KEY_USER_TYPE, 2);
					context.sendBroadcast(intent);
				}
			}
		});
		task.setContext(context);
		task.start();
	}

	public static void setGTClientId(Context context) {
		UserSetRequest req = new UserSetRequest();
		req.token = GlobalSettings.sToken;
		req.GT_ClientID = PushManager.getInstance().getClientid(context);
		UserSetTask task = new UserSetTask();
		task.setRequest(req);
		task.setContext(context);
		task.start();
	}

	public static String getStringToBean(Object obj, String mFileName,
			Context context) {
		AssetManager asset = context.getAssets();
		try {
			InputStream is = asset.open(mFileName);

			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedReader br = new BufferedReader(new InputStreamReader(bis));
			StringBuilder sb = new StringBuilder();
			String s;
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}

			return sb.toString();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * File file = new File("file://android_asset/" + mFileName); if
		 * (file.isFile() && file.exists()) { FileReader fr; try {
		 * 
		 * fr = new FileReader(file); BufferedReader br = new
		 * BufferedReader(fr); StringBuilder sb = new StringBuilder(); String s;
		 * while ((s = br.readLine()) != null) { sb.append(s); }
		 * 
		 * } catch (FileNotFoundException e) { e.printStackTrace(); } catch
		 * (IOException e) { e.printStackTrace(); } catch (Exception e) {
		 * e.printStackTrace(); } }
		 */
		return null;

	}

	public static void putAllAlong(ArrayList<Object> list, JSONArray src) {
		JSONObject object = null;

		ArrayList<Long> ids = new ArrayList<Long>();

		for (int i = 0; i < src.length(); i++) {
			try {
				object = src.getJSONObject(i);

				long qid = object.getLong("Qid");

				if (list.isEmpty()) {
					list.add(object);
					ids.add(qid);
				} else {

					if (!ids.contains(qid)) {
						list.add(object);
						ids.add(qid);
					}

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}
